package ee.videorentalstore.inventories;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class FilmInventory
{
	private static FilmInventory instance = null;
	private Set<Film> filmInventory = new HashSet<Film>();
	private Set<Film> filmsThatAreRentedOut = new HashSet<Film>();
	
	
	private FilmInventory() {}
	
	
	public static FilmInventory getInstance()
	{
		if (instance == null)
		{
			instance = new FilmInventory();
		}
		return instance;
	}
	
	
	public void addNewFilm(Film film)
	{
		filmInventory.add(film);
	}
	
	
	public boolean removeFilm(Film filmToRemove)
	{
		if (filmsThatAreRentedOut.contains(filmToRemove))
		{
			return false;
		}
		
		Iterator<Film> filmInventoryIterator = filmInventory.iterator();
		while (filmInventoryIterator.hasNext())
		{
			Film filmFromInventory = filmInventoryIterator.next();
			if (filmFromInventory.getFilmID() == filmToRemove.getFilmID())
			{
				filmInventoryIterator.remove();
				return true;
			}
		}
		
		return false;
	}
	
	
	public Film getFilmByID(int filmID)
	{
		Film filmToReturn = null;
		
		for (Film film : filmInventory)
		{
			if (film.getFilmID() == filmID)
			{
				filmToReturn = film;
				break;
			}
		}
		
		return filmToReturn;
	}
	
	
	public boolean doesContainFilm(Film film)
	{
		if (filmInventory.contains(film))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	
	public boolean doesContainFilmByID(int filmID)
	{
		if (getFilmByID(filmID) == null)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	
	
	public Set<Film> getAllFilmsInInventory()
	{
		return filmInventory;
	}
	
	
	public Set<Film> getAllAvailableFilmsInInventory()
	{
		Set<Film> allFilmsInFilmInventory = new HashSet<Film>(filmInventory);
		allFilmsInFilmInventory.removeAll(filmsThatAreRentedOut);
		Set<Film> allFilmsThatAreNotRentedOut = new HashSet<Film>();
		allFilmsThatAreNotRentedOut = allFilmsInFilmInventory;
		return allFilmsThatAreNotRentedOut;
	}
	
	
	public void setFilmHasBeenRentedOut(Film film)
	{
		filmsThatAreRentedOut.add(film);
	}
	
	
	public boolean getIsFilmRentedOutByItsID(int filmID)
	{
		boolean hasBeenRentedOut = false;
		for (Film filmThatIsRentedOut : filmsThatAreRentedOut)
		{
			if (filmThatIsRentedOut.getFilmID() == filmID)
			{
				hasBeenRentedOut = true;
				break;
			}
		}
		return hasBeenRentedOut;
	}
}
